<?php


class JWT{

    //头部
    private static $header = array(
        'alg'=>'HS256', //加密算法
        'typ'=>'JWT'    //类型
    );

    //hs秘钥
    private static $secrt = '123456';

    public static function getTocken($payload){
        if (is_array($payload)){
            $base64header = self::base64Encode(json_encode(self::$header,JSON_UNESCAPED_UNICODE));
            $base64payload = self::base64Encode(json_encode($payload,JSON_UNESCAPED_UNICODE));
            $token = $base64header.'.'.$base64payload.'.'.self::signature($base64header.'.'.$base64payload,self::$secrt,self::$header['alg']);
            return $token;
        }else{
            return false;
        }
    }

    public static function verifyToken($token){
        $tokens = explode('.',$token);
        if (count($tokens) != 3){
            return false;
        }
        list($base64header,$base64payload,$sign) = $tokens;

        $debase64header = json_decode(self::base64Decode($base64header),JSON_OBJECT_AS_ARRAY);
        //如果header中没有加密方式，则格式错误
        if (empty($debase64header['alg'])){
            return false;
        }
//        //如果对header和payload重新加密后结果不一致，则token错误
        if (self::signature($base64header.'.'.$base64payload,self::$secrt,$debase64header['alg']) !== $sign){
            return false;
        }

        $payload = json_decode(self::base64Decode($base64payload),JSON_OBJECT_AS_ARRAY);


        //在这里进行时间上的验证等操作即可

        return $payload;
    }

    private static function base64Encode($str){
        return str_replace('=','',strtr(base64_encode($str),'+/','-_'));
    }

    private static function base64Decode($str){
        $remainder = strlen($str)%4;
        if ($remainder){
            $addlen = 4- $remainder;
            $str .= str_repeat('=',$addlen);
        }
        return base64_decode(strtr($str,'-_','+/'));
    }

    private static function signature($str,$key,$alg = 'HS256'){
        $alg_config = array(
            'HS256'=>'sha256'
        );
        return self::base64Encode(hash_hmac($alg_config[$alg],$str,$key,true));
    }


}

//$payload =array(
//    'name'=>'zzn',
//    'age'=>'13',
//    'iat'=>time()
//);
//$token_test = JWT::getTocken($payload);
//echo "<pre>";
//echo $token_test;
//echo "</pre>";
//
//$ver = JWT::verifyToken($token_test);
//echo "<br/>";
//var_dump($ver);
//
